package com.jinyu.jyly.ui.mine.sell;

import android.app.Dialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.jinyu.jyly.R;
import com.jinyu.jyly.adapter.MinePageSellTabAdapter;
import com.jinyu.jyly.adapter.MineSellTabAdapter;
import com.jinyu.jyly.base.BaseLazyFragment;
import com.jinyu.jyly.bean.AllInfoBean;
import com.jinyu.jyly.bean.MineBuyOrderInfo;
import com.jinyu.jyly.bean.OrderListInfo;
import com.jinyu.jyly.utils.AES;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 我的卖单
 *
 * @author 62485
 */
public class MineSellTabFragment extends BaseLazyFragment<MineSellPresenter> implements
        MineSellContract.View, BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener {

    @BindView(R.id.rcv_recycleview)
    RecyclerView rcv_recycleview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.cl_empty)
    ConstraintLayout cl_empty;
    private boolean hasLoadMore = false;
    private boolean isFristLoad = true;
    private int PAGE_NO = 1;
    private int PAGE_SIZE = 10;
    private MineSellPresenter mPresenter;
    private int type;
    private MinePageSellTabAdapter minePageBuyTabAdapter;


    public static MineSellTabFragment newInstance(int type) {
        MineSellTabFragment newFragment = new MineSellTabFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        newFragment.setArguments(bundle);
        return newFragment;
    }


    @Override
    protected View initView(ViewGroup container) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.fragment_mine_buy_tab, container, false);
        return view;
    }

    @Override
    protected void loadData() {
        initInent();
        initRecycleview();
    }

    private void initInent() {
        Bundle arguments = getArguments();
        type = arguments.getInt("type");
        getOrderList();
    }

    private void getOrderList() {
        try {
            //获取mine
            mTipDialog.show();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("cat", "sell"); //37
            jsonObject.put("status", type); //37
            jsonObject.put("page", PAGE_NO);
            String param = AES.encryptToHexString(jsonObject.toString());
//            mPresenter.getOrderList(param);
            mPresenter.getPageOrderList(param);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void initRecycleview() {
        rcv_recycleview.setNestedScrollingEnabled(false);
        rcv_recycleview.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                PAGE_NO = 1;
                try {
                    //获取mine
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("cat", "sell"); //37
                    jsonObject.put("status", type); //37
                    jsonObject.put("page", PAGE_NO);
                    String param = AES.encryptToHexString(jsonObject.toString());
//            mPresenter.getOrderList(param);
                    mPresenter.getPageOrderList(param);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                hasLoadMore = false;
            }
        });

        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                ++PAGE_NO;
                try {
                    //获取mine
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("cat", "sell"); //37
                    jsonObject.put("status", type); //37
                    jsonObject.put("page", PAGE_NO);
                    String param = AES.encryptToHexString(jsonObject.toString());
//            mPresenter.getOrderList(param);
                    mPresenter.getPageOrderList(param);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                hasLoadMore = true;
            }
        });
    }

    @Override
    public MineSellPresenter getPresenter() {
        if (mPresenter == null) {
            mPresenter = new MineSellPresenter(getActivity(), this);
        }
        return mPresenter;
    }


    @Override
    public void onFailer(Throwable throwable) {
        mTipDialog.dismiss();
        mRefreshLayout.finishLoadMore();
        mRefreshLayout.finishRefresh();
        mRefreshLayout.resetNoMoreData();
    }

    @Override
    public void onOrderList(AllInfoBean infoBean) {
        mTipDialog.dismiss();
        mRefreshLayout.finishLoadMore();
        mRefreshLayout.finishRefresh();
        mRefreshLayout.resetNoMoreData();
        switch (infoBean.getStatus()) {
            case 200:
                try {
                    String decrypt = AES.decrypt(infoBean.getData());
                    Gson gson = new Gson();
                    Type listType = new TypeToken<ArrayList<OrderListInfo>>() {
                    }.getType();

                    List<OrderListInfo> mList = gson.fromJson(decrypt, listType);
                    if (mList != null && mList.size() != 0) {
                        cl_empty.setVisibility(View.GONE);
                        rcv_recycleview.setVisibility(View.VISIBLE);

                        MineSellTabAdapter operationAdapter = new MineSellTabAdapter(mList, R.layout.item_mine_sell_tab);
                        rcv_recycleview.setAdapter(operationAdapter);
                        operationAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                            @Override
                            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                                switch (view.getId()) {
                                    case R.id.tv_bottom_shoukuan:
                                        //确认收款
                                        OrderListInfo orderListInfo = mList.get(position);
                                        if (orderListInfo != null) {
                                            int id = orderListInfo.getId();
                                            transferGiftDialog(id);
                                        }
                                        break;
                                }
                            }
                        });
                    } else {
                        cl_empty.setVisibility(View.VISIBLE);
                        rcv_recycleview.setVisibility(View.GONE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 422:
                showToast(infoBean.getMsg());
                break;
            default:
                break;
        }
    }


    /**
     * 转账礼包
     */
    private Dialog mtransferDialog;

    private void transferGiftDialog(int id) {
        mtransferDialog = new Dialog(getActivity(), R.style.wheelviewDialog);
        mtransferDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        View outerView = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_pay_psw, null);
        ImageView iv_close_open = outerView.findViewById(R.id.iv_close_open);
        TextView tv_close = outerView.findViewById(R.id.tv_close);
        TextView tv_sure = outerView.findViewById(R.id.tv_sure);
        TextView payPsw = outerView.findViewById(R.id.et_pay_psw);
        mtransferDialog.setCanceledOnTouchOutside(false);
        mtransferDialog.setContentView(outerView);
        // 将对话框的大小按屏幕大小的百分比设置
        WindowManager windowManager = getActivity().getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        Window window = mtransferDialog.getWindow();
        WindowManager.LayoutParams lp = mtransferDialog.getWindow().getAttributes();
        lp.width = (int) (display.getWidth() * 0.72); //设置宽度
//      lp.height = (int) (display.getHeight() * 0.68);//设置高度
        window.setGravity(Gravity.CENTER);
        window.setAttributes(lp);
        mtransferDialog.show();
        tv_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String psw = payPsw.getText().toString().trim();
                if (TextUtils.isEmpty(psw)) {
                    showToast("支付密码不能为空");
                    return;
                }
                try {
                    //获取mine
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("id", id); //37
                    jsonObject.put("cat", 2); //37
                    jsonObject.put("pwd", psw); //37
                    String param = AES.encryptToHexString(jsonObject.toString());
                    mPresenter.getChangeOrder(param);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                mtransferDialog.dismiss();

            }
        });

        iv_close_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mtransferDialog.dismiss();
            }
        });

        tv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mtransferDialog.dismiss();
            }
        });
    }


    /**
     * 更新订单状态
     *
     * @param infoBean
     */
    @Override
    public void onChangeOrder(AllInfoBean infoBean) {
        mTipDialog.dismiss();
        switch (infoBean.getStatus()) {
            case 200:
                String data = infoBean.getData();
                showToast("更新成功");
                getOrderList();
                break;
            case 422:
                showToast(infoBean.getMsg());
                break;
            default:
                break;
        }
    }

    @Override
    public void onMyGoodList(AllInfoBean infoBean) {
        mTipDialog.dismiss();
    }

    @Override
    public void onPageMyGoodList(AllInfoBean infoBean) {
        //空
    }

    /**
     * 我的卖单
     *
     * @param infoBean
     */
    @Override
    public void onPageOrderList(AllInfoBean infoBean) {
        mTipDialog.dismiss();
        mRefreshLayout.finishLoadMore();
        mRefreshLayout.finishRefresh();
        mRefreshLayout.resetNoMoreData();
        switch (infoBean.getStatus()) {
            case 200:
                try {
                    String decrypt = AES.decrypt(infoBean.getData());
                    Gson gson = new Gson();
                    MineBuyOrderInfo mineBuyOrderInfo = gson.fromJson(decrypt, MineBuyOrderInfo.class);
                    if (mineBuyOrderInfo != null) {
                        int page = mineBuyOrderInfo.getPage();
                        if (isFristLoad) {
                            List<MineBuyOrderInfo.DataBean> dataBeanList = mineBuyOrderInfo.getData();
                            minePageBuyTabAdapter = new MinePageSellTabAdapter(dataBeanList, R.layout.item_mine_sell_tab,getActivity());
                            rcv_recycleview.setAdapter(minePageBuyTabAdapter);
                            minePageBuyTabAdapter.setOnItemChildClickListener(this);
                            isFristLoad = false;
                        } else {
                            if (!hasLoadMore) {
                                //下拉加载
                                List<MineBuyOrderInfo.DataBean> dataBeanList = mineBuyOrderInfo.getData();
                                minePageBuyTabAdapter.replaceData(dataBeanList);
                            } else {
                                //上拉加载
                                if (PAGE_NO <= page) {
                                    //说明有值
                                    List<MineBuyOrderInfo.DataBean> dataBeanList = mineBuyOrderInfo.getData();
                                    minePageBuyTabAdapter.addData(dataBeanList);
                                }
                            }
                        }

                        List<MineBuyOrderInfo.DataBean> dataList = minePageBuyTabAdapter.getData();
                        if (dataList != null && dataList.size() != 0) {
                            cl_empty.setVisibility(View.GONE);
                            rcv_recycleview.setVisibility(View.VISIBLE);
                        } else {
                            cl_empty.setVisibility(View.VISIBLE);
                            rcv_recycleview.setVisibility(View.GONE);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 422:
                showToast(infoBean.getMsg());
                break;
            default:
                break;
        }
    }


    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        if (minePageBuyTabAdapter != null) {
            List<MineBuyOrderInfo.DataBean> dataList = minePageBuyTabAdapter.getData();
            if (dataList != null && dataList.size() != 0) {
                MineBuyOrderInfo.DataBean dataBean = dataList.get(position);
                if (dataBean != null) {
                    int id = dataBean.getId();
                    switch (view.getId()) {
                        case R.id.tv_bottom_shoukuan:
                            //确认收款
                            transferGiftDialog(id);
                            break;
                    }
                }
            }
        }
    }
}
